/**
 * @summary: 简易 fixed 元素拖拽实现
 * @author: lixinxiang@vv.cn
 */
import React, { useState, useCallback, forwardRef, useRef } from 'react';

const Draggable = ({ className, children, ...restProps }) => {
    const draggableRef = useRef();
    const draggingRef = useRef();

    const [state, setState] = useState({ x: 'auto', y: 'auto' });

    const handleMouseMove = useCallback(
        ({ clientX, clientY }) => {
            const { width, height } = draggableRef.current.getBoundingClientRect();
            if (!draggingRef.current) {
                return;
            }
            setState({
                x: clientX - width / 2,
                y: clientY - height / 2
            });
        },
        [state]
    );

    const handleMouseUp = useCallback(() => {
        draggingRef.current = false;
        window.removeEventListener('mousemove', handleMouseMove);
        window.removeEventListener('mouseup', handleMouseUp);
    }, []);

    const handleMouseDown = useCallback(e => {
        e.preventDefault();
        draggingRef.current = true;
        window.addEventListener('mousemove', handleMouseMove);
        window.addEventListener('mouseup', handleMouseUp);
    }, []);

    return (
        <div
            {...restProps}
            ref={draggableRef}
            style={{ left: state.x, top: state.y }}
            onMouseDown={handleMouseDown}
            className={className}
            draggable={false}
        >
            {children}
        </div>
    );
};

export default forwardRef(Draggable);
